<template>
  <div class="exam-container">
    <!-- 顶部固定栏 - 简洁版 -->
    <div class="fixed-header">
      <div class="countdown-timer">
        剩余时间：{{ countdownTime }}
      </div>
    </div>

    <!-- 全屏提示 -->
    <div v-if="showFullscreenPrompt" class="fullscreen-prompt">
      建议进入全屏模式以获得更好的考试体验
      <el-button type="primary" plain @click="enterFullscreen" size="small">进入全屏</el-button>
    </div>

    <!-- 加载状态 -->
    <div v-if="isLoading" class="loading-container">
      <el-spinner class="loading-spinner" type="circular" size="40"></el-spinner>
      <div class="loading-text">正在加载试卷...</div>
    </div>

    <!-- 错误信息 -->
    <el-alert v-else-if="errorMessage" type="error" show-icon :message="errorMessage" class="error-alert"></el-alert>

    <!-- 试卷内容和答题卡容器 -->
    <div v-else-if="examData" class="exam-content-wrapper">
      <!-- 试卷内容 -->
      <div class="content-section">
        <!-- 试卷头部信息 - 简化版 -->
        <div class="exam-header">
          <h2 class="exam-title">{{ examData.examType }} 模拟试卷</h2>
          <div class="exam-meta">
            <span>组卷策略：{{ getStrategyName(examData.examStrategy) }}</span>
            <span>题目总数：{{ examData.questions.length }} 题</span>
            <span>考试时长：{{ examData.totalTime }} 分钟</span>
            <span>已答题：{{ answeredCount }}/{{ examData.questions.length }}</span>
          </div>
        </div>

        <!-- 题型导航 - 智能固定版 -->
        <div class="question-nav-container" ref="navContainerRef">
          <div 
            class="question-nav" 
            :class="{ sticky: isNavSticky }" 
            ref="questionNavRef"
          >
            <div 
              v-if="singleChoiceIndexes.length" 
              class="nav-item" 
              :class="{ active: currentTab === 'single' }"
              @click="switchTab('single')"
            >
              单选题 ({{ singleChoiceIndexes.length }})
            </div>
            
            <div 
              v-if="fillInTheBlankIndexes.length" 
              class="nav-item" 
              :class="{ active: currentTab === 'fill' }"
              @click="switchTab('fill')"
            >
              填空题 ({{ fillInTheBlankIndexes.length }})
            </div>
            
            <div 
              v-if="subjectiveIndexes.length" 
              class="nav-item" 
              :class="{ active: currentTab === 'subjective' }"
              @click="switchTab('subjective')"
            >
              主观题 ({{ subjectiveIndexes.length }})
            </div>
          </div>
        </div>

        <!-- 题目列表 -->
        <div class="questions-list">
          <!-- 单选题部分 -->
          <div v-if="currentTab === 'single' && singleChoiceIndexes.length">
            <div class="section-title">单选题（每题5分）</div>
            
            <div 
              v-for="index in singleChoiceIndexes" 
              :key="examData.questions[index].questionId"
              :id="`question-${index}`"
              class="question-item"
            >
              <div class="question-header">
                <span class="question-number">{{ index + 1 }}.</span>
                <span class="question-status" :class="{ answered: isAnswered(index) }">
                  {{ isAnswered(index) ? '已答' : '未答' }}
                </span>
              </div>

              <div class="question-content" v-html="formatQuestionContent(examData.questions[index].content)"></div>

              <div class="options-list">
                <el-radio-group v-model="userAnswers[index]" class="options-grid">
                  <div 
                    v-for="(option, key) in examData.questions[index].optionsMap" 
                    :key="key" 
                    class="option-item"
                  >
                    <el-radio :label="key">
                      <span class="option-label">{{ key }}.</span>
                      <span class="option-text" v-html="formatQuestionContent(option)"></span>
                    </el-radio>
                  </div>
                </el-radio-group>
              </div>

              <!-- 题型跳转按钮 - 只在题型最后一题显示 -->
              <div v-if="shouldShowTypeNavigation(index)" class="type-navigation">
                <div class="navigation-buttons">
                  <el-button 
                    v-if="getNextTypeFirstQuestion(index) !== -1"
                    @click="jumpToNextType(index)" 
                    type="primary"
                    size="default"
                  >
                    继续答题：{{ getNextTypeName(index) }} →
                  </el-button>
                  <el-button 
                    v-else
                    @click="submitExam" 
                    type="success"
                    size="default"
                  >
                    提交试卷
                  </el-button>
                </div>
              </div>
            </div>
          </div>

          <!-- 填空题部分 -->
          <div v-if="currentTab === 'fill' && fillInTheBlankIndexes.length">
            <div class="section-title">填空题（每题5分）</div>
            
            <div 
              v-for="index in fillInTheBlankIndexes" 
              :key="examData.questions[index].questionId"
              :id="`question-${index}`"
              class="question-item"
            >
              <div class="question-header">
                <span class="question-number">{{ index + 1 }}.</span>
                <span class="question-status" :class="{ answered: isAnswered(index) }">
                  {{ isAnswered(index) ? '已答' : '未答' }}
                </span>
              </div>

              <div class="question-content" v-html="formatQuestionContent(examData.questions[index].content)"></div>

              <div class="answer-input">
                <el-input 
                  v-model="userAnswers[index]" 
                  placeholder="请输入答案" 
                  class="fill-input"
                  clearable
                />
              </div>

              <!-- 题型跳转按钮 - 只在题型最后一题显示 -->
              <div v-if="shouldShowTypeNavigation(index)" class="type-navigation">
                <div class="navigation-buttons">
                  <el-button 
                    v-if="getNextTypeFirstQuestion(index) !== -1"
                    @click="jumpToNextType(index)" 
                    type="primary"
                    size="default"
                  >
                    继续答题：{{ getNextTypeName(index) }} →
                  </el-button>
                  <el-button 
                    v-else
                    @click="submitExam" 
                    type="success"
                    size="default"
                  >
                    提交试卷
                  </el-button>
                </div>
              </div>
            </div>
          </div>

          <!-- 主观题部分 -->
          <div v-if="currentTab === 'subjective' && subjectiveIndexes.length">
            <div class="section-title">主观题（需写出详细解答过程）</div>
            
            <div 
              v-for="index in subjectiveIndexes" 
              :key="examData.questions[index].questionId"
              :id="`question-${index}`"
              class="question-item"
            >
              <div class="question-header">
                <span class="question-number">{{ index + 1 }}.</span>
                <span class="question-status" :class="{ answered: isAnswered(index) }">
                  {{ isAnswered(index) ? '已答' : '未答' }}
                </span>
              </div>

              <div class="question-content" v-html="formatQuestionContent(examData.questions[index].content)"></div>

              <div class="answer-input">
                <el-input 
                  type="textarea" 
                  v-model="userAnswers[index]" 
                  placeholder="请书写详细解题过程和答案..." 
                  :rows="8"
                  class="subjective-input"
                  show-word-limit
                  maxlength="2000"
                />
              </div>

              <!-- 题型跳转按钮 - 只在题型最后一题显示 -->
              <div v-if="shouldShowTypeNavigation(index)" class="type-navigation">
                <div class="navigation-buttons">
                  <el-button 
                    v-if="getNextTypeFirstQuestion(index) !== -1"
                    @click="jumpToNextType(index)" 
                    type="primary"
                    size="default"
                  >
                    继续答题：{{ getNextTypeName(index) }} →
                  </el-button>
                  <el-button 
                    v-else
                    @click="submitExam" 
                    type="success"
                    size="default"
                  >
                    提交试卷
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧答题卡 - 简化版 -->
      <div class="answer-card">
        <div class="card-header">
          <div class="card-title">答题卡</div>
          <div class="progress-text">
            进度：<span class="progress-numbers">{{ answeredCount }}/{{ examData.questions.length }}</span>
          </div>
        </div>

        <div class="card-body">
          <!-- 单选题区域 -->
          <div v-if="singleChoiceIndexes.length" class="question-type-section">
            <div class="type-title">单选题</div>
            <div class="question-grid">
              <div 
                v-for="index in singleChoiceIndexes" 
                :key="index" 
                class="question-number-btn" 
                :class="{
                  'answered': isAnswered(index),
                  'current': currentQuestion === index
                }" 
                @click="jumpToQuestion(index)"
              >
                {{ index + 1 }}
              </div>
            </div>
          </div>

          <!-- 填空题区域 -->
          <div v-if="fillInTheBlankIndexes.length" class="question-type-section">
            <div class="type-title">填空题</div>
            <div class="question-grid">
              <div 
                v-for="index in fillInTheBlankIndexes" 
                :key="index" 
                class="question-number-btn" 
                :class="{
                  'answered': isAnswered(index),
                  'current': currentQuestion === index
                }" 
                @click="jumpToQuestion(index)"
              >
                {{ index + 1 }}
              </div>
            </div>
          </div>

          <!-- 主观题区域 -->
          <div v-if="subjectiveIndexes.length" class="question-type-section">
            <div class="type-title">主观题</div>
            <div class="question-grid">
              <div 
                v-for="index in subjectiveIndexes" 
                :key="index" 
                class="question-number-btn" 
                :class="{
                  'answered': isAnswered(index),
                  'current': currentQuestion === index
                }" 
                @click="jumpToQuestion(index)"
              >
                {{ index + 1 }}
              </div>
            </div>
          </div>
        </div>

        <!-- 提交按钮 -->
        <div class="card-footer">
          <el-button 
            type="primary" 
            size="large" 
            @click="submitExam" 
            class="submit-button"
          >
            提交试卷
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted, watch, computed, nextTick } from 'vue';
import { ElMessageBox } from 'element-plus';
import axios from 'axios';
import { useRoute, useRouter } from 'vue-router';
import { useUserStore } from '@/store/user';

// 导入KaTeX和markdown-it相关库
import 'katex/dist/katex.min.css';
import katex from 'katex';
import MarkdownIt from 'markdown-it';
import markdownItKatex from 'markdown-it-katex';

export default {
  setup() {
    const route = useRoute();
    const router = useRouter();
    const userStore = useUserStore();

    // 配置markdown-it和KaTeX
    const md = new MarkdownIt({
      html: true,        // 允许HTML标签
      breaks: true,      // 转换换行符
      linkify: true      // 自动转换链接
    }).use(markdownItKatex, {
      // KaTeX配置选项
      throwOnError: false,
      errorColor: '#cc0000',
      strict: false,
      trust: true,
      output: 'html'
    });

    const submitData = ref({
      userId: null,
      examType: '',
      examStrategy: '',
      totalTime: 0,
      questions: [],
    });
    const examData = ref(null);
    const isLoading = ref(true);
    const errorMessage = ref('');
    const userAnswers = ref([]);
    const countdownTime = ref('03:00:00');
    const countdownInterval = ref(null);
    const isFullscreen = ref(false);
    const showFullscreenPrompt = ref(false);
    const currentQuestion = ref(0);
    const currentTab = ref('single'); // 当前题型分页
    const isNavSticky = ref(false); // 导航是否粘性固定
    const questionNavRef = ref(null); // 导航元素引用
    const navContainerRef = ref(null); // 导航容器引用
    const navOriginalTop = ref(0); // 导航原始位置

    const answeredCount = ref(0);

    const singleChoiceIndexes = computed(() => {
      if (!examData.value) return [];
      return examData.value.questions.reduce((indexes, question, index) => {
        if (question.questionType === 'single_choice') indexes.push(index);
        return indexes;
      }, []);
    });

    const fillInTheBlankIndexes = computed(() => {
      if (!examData.value) return [];
      return examData.value.questions.reduce((indexes, question, index) => {
        if (question.questionType === 'fill_in_the_blank') indexes.push(index);
        return indexes;
      }, []);
    });

    const subjectiveIndexes = computed(() => {
      if (!examData.value) return [];
      return examData.value.questions.reduce((indexes, question, index) => {
        if (question.questionType === 'subjective') indexes.push(index);
        return indexes;
      }, []);
    });

    watch(userAnswers, (newAnswers) => {
      answeredCount.value = newAnswers.filter(answer =>
        answer !== '' && answer !== null && answer !== undefined
      ).length;
    }, { deep: true });

    // 格式化题目内容 - 使用KaTeX和markdown-it处理
    const formatQuestionContent = (content) => {
      if (!content) return '';
      
      try {
        // 预处理内容
        let processedContent = content
          .replace(/\\n/g, '\n')  // 处理换行符
          .replace(/\\\$/g, '###DOLLAR###')  // 临时替换转义的美元符号
          .replace(/\$\$([^$]+)\$\$/g, (match, formula) => {
            // 处理块级数学公式 $$...$$
            try {
              return katex.renderToString(formula.trim(), {
                displayMode: true,
                throwOnError: false,
                strict: false,
                trust: true
              });
            } catch (error) {
              console.warn('KaTeX block formula error:', error, 'Formula:', formula);
              return `<span class="katex-error">$$${formula}$$</span>`;
            }
          })
          .replace(/\$([^$\n]+)\$/g, (match, formula) => {
            // 处理行内数学公式 $...$
            try {
              return katex.renderToString(formula.trim(), {
                displayMode: false,
                throwOnError: false,
                strict: false,
                trust: true
              });
            } catch (error) {
              console.warn('KaTeX inline formula error:', error, 'Formula:', formula);
              return `<span class="katex-error">$${formula}$</span>`;
            }
          })
          .replace(/###DOLLAR###/g, '$');  // 恢复转义的美元符号
        
        // 使用markdown-it处理其他格式
        const htmlContent = md.render(processedContent);
        
        return htmlContent;
      } catch (error) {
        console.error('formatQuestionContent error:', error);
        return content.replace(/\\n/g, '<br>');
      }
    };

    // 优化的智能粘性导航处理
    const handleNavSticky = () => {
      if (!navContainerRef.value) return;
      
      const containerRect = navContainerRef.value.getBoundingClientRect();
      const headerHeight = 60;
      
      // 当导航容器顶部即将被顶部固定栏遮挡时固定
      if (containerRect.top <= headerHeight) {
        if (!isNavSticky.value) {
          isNavSticky.value = true;
        }
      } else {
        if (isNavSticky.value) {
          isNavSticky.value = false;
        }
      }
    };

    // 记录导航栏原始位置
    const recordNavPosition = () => {
      if (navContainerRef.value) {
        const rect = navContainerRef.value.getBoundingClientRect();
        navOriginalTop.value = rect.top + window.pageYOffset;
      }
    };

    // 获取题型内的题目索引
    const getQuestionTypeInfo = (questionIndex) => {
      const question = examData.value.questions[questionIndex];
      let typeIndexes = [];
      let positionInType = -1;
      
      if (question.questionType === 'single_choice') {
        typeIndexes = singleChoiceIndexes.value;
      } else if (question.questionType === 'fill_in_the_blank') {
        typeIndexes = fillInTheBlankIndexes.value;
      } else if (question.questionType === 'subjective') {
        typeIndexes = subjectiveIndexes.value;
      }
      
      positionInType = typeIndexes.indexOf(questionIndex);
      
      return {
        typeIndexes,
        positionInType,
        isLastInType: positionInType === typeIndexes.length - 1,
        questionType: question.questionType
      };
    };

    // 获取下一个题型的第一题
    const getNextTypeFirstQuestion = (currentQuestionIndex) => {
      const { questionType } = getQuestionTypeInfo(currentQuestionIndex);
      
      if (questionType === 'single_choice' && fillInTheBlankIndexes.value.length > 0) {
        return fillInTheBlankIndexes.value[0];
      } else if (questionType === 'fill_in_the_blank' && subjectiveIndexes.value.length > 0) {
        return subjectiveIndexes.value[0];
      }
      
      return -1; // 没有下一个题型
    };

    // 判断是否应该显示题型跳转按钮
    const shouldShowTypeNavigation = (questionIndex) => {
      const { isLastInType } = getQuestionTypeInfo(questionIndex);
      return isLastInType;
    };

    // 获取下一个题型的名称
    const getNextTypeName = (currentQuestionIndex) => {
      const { questionType } = getQuestionTypeInfo(currentQuestionIndex);
      
      if (questionType === 'single_choice' && fillInTheBlankIndexes.value.length > 0) {
        return '填空题';
      } else if (questionType === 'fill_in_the_blank' && subjectiveIndexes.value.length > 0) {
        return '主观题';
      }
      
      return '';
    };

    // 跳转到下一个题型
    const jumpToNextType = (currentQuestionIndex) => {
      const nextQuestionIndex = getNextTypeFirstQuestion(currentQuestionIndex);
      if (nextQuestionIndex !== -1) {
        const question = examData.value.questions[nextQuestionIndex];
        
        // 先切换tab
        if (question.questionType === 'single_choice') {
          currentTab.value = 'single';
        } else if (question.questionType === 'fill_in_the_blank') {
          currentTab.value = 'fill';
        } else if (question.questionType === 'subjective') {
          currentTab.value = 'subjective';
        }
        
        // 等待DOM更新后再跳转
        nextTick(() => {
          jumpToQuestion(nextQuestionIndex);
        });
      }
    };

    const switchTab = (tab) => {
      currentTab.value = tab;
      // 切换到对应题型的第一题
      let targetIndex = 0;
      switch (tab) {
        case 'single':
          if (singleChoiceIndexes.value.length) {
            targetIndex = singleChoiceIndexes.value[0];
          }
          break;
        case 'fill':
          if (fillInTheBlankIndexes.value.length) {
            targetIndex = fillInTheBlankIndexes.value[0];
          }
          break;
        case 'subjective':
          if (subjectiveIndexes.value.length) {
            targetIndex = subjectiveIndexes.value[0];
          }
          break;
      }
      jumpToQuestion(targetIndex);
    };

    // 获取选择题详情
    const fetchChoiceQuestionDetail = async (questionId) => {
      try {
        const response = await axios.get(`/api/exam/question/${questionId}`);
        if (response.data.code === 200) {
          const detail = response.data.data;
          if (!detail.optionsMap || Object.keys(detail.optionsMap).length === 0) {
            detail.optionsMap = {
              A: "选项A",
              B: "选项B", 
              C: "选项C",
              D: "选项D"
            };
          }
          return detail;
        }
        return null;
      } catch (error) {
        console.error('获取选择题详情失败:', error);
        return {
          optionsMap: {
            A: "选项A",
            B: "选项B",
            C: "选项C",
            D: "选项D"
          },
          answer: "A"
        };
      }
    };

    // 加载历年套卷逻辑
    const fetchPastExamQuestions = async (examType, examYear) => {
      try {
        const response = await axios.get('/api/exam/past-exam-questions', {
          params: {
            examType: examType,
            year: examYear
          }
        });

        if (response.data.code === 200) {
          const questions = response.data.data;

          const questionDetails = await Promise.all(
            questions.map(async (question) => {
              if (question.questionType === 'single_choice') {
                const detail = await fetchChoiceQuestionDetail(question.questionId);
                return detail
                  ? { ...question, optionsMap: detail.optionsMap }
                  : question;
              }
              return question;
            })
          );

          examData.value = {
            examType: examType,
            examStrategy: `${examYear}年${examType}真题`,
            questions: questionDetails,
            totalTime: 180
          };

          userAnswers.value = new Array(examData.value.questions.length).fill('');

          submitData.value = {
            userId: userStore.userId,
            examType: examData.value.examType,
            examStrategy: examData.value.examStrategy,
            totalTime: examData.value.totalTime,
            questions: examData.value.questions.map(question => ({
              questionId: question.questionId,
              questionType: question.questionType,
            })),
          };

          // 设置默认显示的题型
          if (singleChoiceIndexes.value.length) {
            currentTab.value = 'single';
          } else if (fillInTheBlankIndexes.value.length) {
            currentTab.value = 'fill';
          } else if (subjectiveIndexes.value.length) {
            currentTab.value = 'subjective';
          }
        } else {
          throw new Error(response.data.msg || '加载历年套卷失败');
        }
      } catch (error) {
        console.error('加载历年套卷失败:', error);
        errorMessage.value = error.message || '加载历年套卷失败，请重试';
      } finally {
        isLoading.value = false;
      }
    };

    onMounted(async () => {
      try {
        const examId = route.query.examId;
        const isPastExam = route.query.isPastExam;
        const examType = route.query.examType;
        const examYear = route.query.examYear;

        isLoading.value = true;

        // 隐藏导航栏
        const navbar = document.querySelector('.navbar');
        if (navbar) {
          navbar.style.display = 'none';
        }

        if (isPastExam) {
          await fetchPastExamQuestions(examType, examYear);
        } else if (examId) {
          const response = await axios.get(`/api/exam/${examId}/questions`);
          if (response.data.code !== 200) throw new Error(response.data.msg);

          examData.value = response.data.data;
          userAnswers.value = new Array(examData.value.questions.length).fill('');

          submitData.value = {
            userId: userStore.userId,
            examType: examData.value.examType,
            examStrategy: examData.value.examStrategy,
            totalTime: examData.value.totalTime,
            questions: examData.value.questions.map(question => ({
              questionId: question.questionId,
              questionType: question.questionType,
            })),
          };

          // 设置默认显示的题型
          if (singleChoiceIndexes.value.length) {
            currentTab.value = 'single';
          } else if (fillInTheBlankIndexes.value.length) {
            currentTab.value = 'fill';
          } else if (subjectiveIndexes.value.length) {
            currentTab.value = 'subjective';
          }
        } else {
          throw new Error('缺少试卷参数');
        }

        if (examData.value && examData.value.totalTime) {
          startCountdown(examData.value.totalTime);
        } else {
          startCountdown(180);
        }

        enterFullscreen();
        document.addEventListener('fullscreenchange', handleFullscreenChange);
        window.addEventListener('scroll', handleScroll);
        window.addEventListener('scroll', handleNavSticky);
        
        // 等待DOM渲染完成后记录导航位置
        nextTick(() => {
          recordNavPosition();
        });
      } catch (error) {
        console.error('加载试卷失败:', error);
        errorMessage.value = error.message || '加载试卷失败，请重试';
      } finally {
        isLoading.value = false;
      }
    });

    onUnmounted(() => {
      if (countdownInterval.value) {
        clearInterval(countdownInterval.value);
      }
      document.removeEventListener('fullscreenchange', handleFullscreenChange);
      window.removeEventListener('scroll', handleScroll);
      window.removeEventListener('scroll', handleNavSticky);
      
      // 恢复导航栏显示
      const navbar = document.querySelector('.navbar');
      if (navbar) {
        navbar.style.display = 'flex';
      }
    });

    const isAnswered = (index) => {
      return userAnswers.value[index] !== '' &&
        userAnswers.value[index] !== null &&
        userAnswers.value[index] !== undefined;
    };

    const jumpToQuestion = (index) => {
      if (!examData.value || !examData.value.questions[index]) return;
      
      const question = examData.value.questions[index];
      
      // 先切换到正确的题型标签页
      if (question.questionType === 'single_choice') {
        currentTab.value = 'single';
      } else if (question.questionType === 'fill_in_the_blank') {
        currentTab.value = 'fill';
      } else if (question.questionType === 'subjective') {
        currentTab.value = 'subjective';
      }
      
      // 等待DOM更新后再执行跳转
      nextTick(() => {
        const element = document.getElementById(`question-${index}`);
        if (element) {
          const headerHeight = document.querySelector('.fixed-header')?.offsetHeight || 60;
          const stickyNavHeight = isNavSticky.value ? 60 : 0;
          const elementPosition = element.getBoundingClientRect().top + window.pageYOffset;
          const offsetPosition = elementPosition - headerHeight - stickyNavHeight - 20;

          window.scrollTo({
            top: offsetPosition,
            behavior: 'smooth'
          });

          // 更新当前题目索引
          currentQuestion.value = index;
          
          // 添加高亮效果
          element.style.transition = 'all 0.3s ease';
          element.style.transform = 'scale(1.02)';
          element.style.boxShadow = '0 4px 20px rgba(0, 123, 255, 0.3)';
          
          // 1秒后移除高亮效果
          setTimeout(() => {
            element.style.transform = 'scale(1)';
            element.style.boxShadow = '0 1px 3px rgba(0, 0, 0, 0.1)';
          }, 1000);
        }
      });
    };

    const handleScroll = () => {
      if (!examData.value) return;

      const scrollPosition = window.scrollY + 150;
      let closestIndex = 0;
      let minDistance = Infinity;

      for (let i = 0; i < examData.value.questions.length; i++) {
        const element = document.getElementById(`question-${i}`);
        if (element) {
          const rect = element.getBoundingClientRect();
          const distance = Math.abs(rect.top);

          if (distance < minDistance) {
            minDistance = distance;
            closestIndex = i;
          }
        }
      }

      currentQuestion.value = closestIndex;
    };

    const enterFullscreen = () => {
      const element = document.documentElement;
      if (element.requestFullscreen) {
        element.requestFullscreen().catch(err => {
          console.log(`全屏请求被拒绝: ${err}`);
          showFullscreenPrompt.value = true;
        });
      }
    };

    const handleFullscreenChange = () => {
      isFullscreen.value = !!document.fullscreenElement;
      showFullscreenPrompt.value = !isFullscreen.value;
    };

    const startCountdown = (minutes) => {
      let seconds = minutes * 60;

      countdownInterval.value = setInterval(() => {
        seconds--;

        if (seconds < 0) {
          clearInterval(countdownInterval.value);
          // 时间到了，强制提交
          forceSubmitExam();
          return;
        }

        const hours = Math.floor(seconds / 3600);
        const mins = Math.floor((seconds % 3600) / 60);
        const secs = seconds % 60;

        countdownTime.value =
          `${hours.toString().padStart(2, '0')}:${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
      }, 1000);
    };

    const getStrategyName = (strategy) => {
      const strategyMap = {
        random: '完全随机',
        weakness: '薄弱知识点',
        high_frequency: '高频易错题',
        custom: '定向知识点'
      };
      return strategyMap[strategy] || strategy;
    };

    const getQuestionTypeName = (type) => {
      const typeMap = {
        single_choice: '单选题',
        fill_in_the_blank: '填空题',
        subjective: '主观题'
      };
      return typeMap[type] || type;
    };

    const forceSubmitExam = async () => {
      try {
        // 时间到了，显示提示并强制提交
        ElMessageBox.alert(
          '考试时间已到，系统将自动提交您的答卷。',
          '考试时间结束',
          {
            confirmButtonText: '确定',
            type: 'warning',
            center: true,
            showClose: false,
            closeOnClickModal: false,
            closeOnPressEscape: false
          }
        );

        const submissionData = {
          userId: userStore.userId,
          examType: examData.value.examType,
          examStrategy: examData.value.examStrategy || `${route.query.examYear}年${route.query.examType}真题`,
          totalScore: 100,
          timeLimit: examData.value.totalTime || 180,
          questions: examData.value.questions.map((question, index) => ({
            questionId: question.questionId,
            userAnswer: userAnswers.value[index] || '',
            questionType: question.questionType,
            sequence: index + 1,
            isCorrect: null
          })),
          isPastExam: !!route.query.isPastExam,
          examYear: route.query.isPastExam ? parseInt(route.query.examYear) : null
        };

        const response = await axios.post('/api/exam/submit', submissionData, {
          headers: {
            'userId': userStore.userId.toString()
          }
        });
        
        // 恢复导航栏显示
        const navbar = document.querySelector('.navbar');
        if (navbar) {
          navbar.style.display = 'flex';
        }
        
        if (document.fullscreenElement) {
          document.exitFullscreen().catch(err => {
            console.log(`退出全屏失败: ${err}`);
          });
        }

        if (response.data.code === 200) {
          const resultData = response.data.data;
          const isPastExam = route.query.isPastExam;
          
          if (isPastExam) {
            router.push({
              name: 'PastExamDetail',
              params: { 
                recordId: resultData.recordId 
              }
            });
          } else {
            router.push({
              name: 'MockExamDetail',
              params: { 
                examId: resultData.examId 
              }
            });
          }
        }
      } catch (error) {
        errorMessage.value = error.response?.data?.message || error.message || '提交失败，请重试';
      }
    };

    const submitExam = async () => {
      try {
        // 计算答题统计
        const totalQuestions = examData.value.questions.length;
        const answeredQuestions = userAnswers.value.filter(answer =>
          answer !== '' && answer !== null && answer !== undefined
        ).length;
        const unansweredQuestions = totalQuestions - answeredQuestions;
        
        // 构建确认消息
        let confirmMessage = `<div style="text-align: left; line-height: 1.6;">
          <p style="margin-bottom: 10px;"><strong>📊 答题统计：</strong></p>
          <p style="margin-bottom: 8px;">• 总题数：<span style="color: #409EFF; font-weight: bold;">${totalQuestions}</span> 题</p>
          <p style="margin-bottom: 8px;">• 已答题：<span style="color: #67C23A; font-weight: bold;">${answeredQuestions}</span> 题</p>
          <p style="margin-bottom: 15px;">• 未答题：<span style="color: #F56C6C; font-weight: bold;">${unansweredQuestions}</span> 题</p>`;
        
        if (unansweredQuestions > 0) {
          confirmMessage += `<p style="color: #E6A23C; font-weight: bold; margin-bottom: 10px;">⚠️ 您还有 ${unansweredQuestions} 道题未作答</p>`;
        }
        
        confirmMessage += `<p style="margin-bottom: 0;">确定要提交试卷吗？提交后将无法修改答案。</p></div>`;

        // 显示确认对话框
        await ElMessageBox.confirm(
          confirmMessage,
          '确认提交试卷',
          {
            confirmButtonText: '确定提交',
            cancelButtonText: '继续答题',
            type: 'warning',
            dangerouslyUseHTMLString: true,
            center: true,
            customStyle: {
              width: '420px'
            },
            customClass: 'submit-confirm-dialog'
          }
        );

        // 用户确认提交，执行实际提交逻辑
        const submissionData = {
          userId: userStore.userId,
          examType: examData.value.examType,
          examStrategy: examData.value.examStrategy || `${route.query.examYear}年${route.query.examType}真题`,
          totalScore: 100,
          timeLimit: examData.value.totalTime || 180,
          questions: examData.value.questions.map((question, index) => ({
            questionId: question.questionId,
            userAnswer: userAnswers.value[index] || '',
            questionType: question.questionType,
            sequence: index + 1,
            isCorrect: null
          })),
          isPastExam: !!route.query.isPastExam,
          examYear: route.query.isPastExam ? parseInt(route.query.examYear) : null
        };

        const response = await axios.post('/api/exam/submit', submissionData, {
          headers: {
            'userId': userStore.userId.toString()
          }
        });
        
        // 恢复导航栏显示
        const navbar = document.querySelector('.navbar');
        if (navbar) {
          navbar.style.display = 'flex';
        }
        
        if (document.fullscreenElement) {
          document.exitFullscreen().catch(err => {
            console.log(`退出全屏失败: ${err}`);
          });
        }

        if (response.data.code === 200) {
          const resultData = response.data.data;
          const isPastExam = route.query.isPastExam;
          
          if (isPastExam) {
            router.push({
              name: 'PastExamDetail',
              params: { 
                recordId: resultData.recordId 
              }
            });
          } else {
            router.push({
              name: 'MockExamDetail',
              params: { 
                examId: resultData.examId 
              }
            });
          }
        }
      } catch (error) {
        // 如果是用户取消操作，不显示错误信息
        if (error === 'cancel') {
          return;
        }
        errorMessage.value = error.response?.data?.message || error.message || '提交失败，请重试';
      }
    };

    return {
      examData,
      isLoading,
      errorMessage,
      userAnswers,
      countdownTime,
      showFullscreenPrompt,
      answeredCount,
      currentQuestion,
      currentTab,
      formatQuestionContent,
      getStrategyName,
      getQuestionTypeName,
      submitExam,
      forceSubmitExam,
      enterFullscreen,
      isAnswered,
      jumpToQuestion,
      jumpToNextType,
      switchTab,
      shouldShowTypeNavigation,
      getNextTypeFirstQuestion,
      getNextTypeName,
      isNavSticky,
      questionNavRef,
      navContainerRef,
      singleChoiceIndexes,
      fillInTheBlankIndexes,
      subjectiveIndexes
    };
  }
};
</script>

<style scoped>
/* 基础布局 - 简洁版 */
.exam-container {
  min-height: 100vh;
  background-color: #fafafa;
  padding: 80px 20px 20px 20px;
}

.exam-content-wrapper {
  max-width: 1400px;
  margin: 0 auto;
  display: flex;
  gap: 30px;
}

.content-section {
  flex: 1;
  min-width: 0;
}

/* 顶部固定栏 - 简化版 */
.fixed-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 60px;
  background-color: #ffffff;
  border-bottom: 2px solid #e8e8e8;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.countdown-timer {
  font-size: 1.4rem;
  font-weight: 600;
  color: #d32f2f;
  font-family: 'Courier New', monospace;
}

/* 全屏提示 */
.fullscreen-prompt {
  position: fixed;
  top: 60px;
  left: 0;
  right: 0;
  background-color: #fff3cd;
  color: #856404;
  padding: 10px;
  text-align: center;
  z-index: 999;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 15px;
  border-bottom: 1px solid #ffeaa7;
}

/* 试卷头部 - 简化版 */
.exam-header {
  background: white;
  padding: 25px;
  border-radius: 8px;
  margin-bottom: 20px;
  border: 1px solid #e0e0e0;
}

.exam-title {
  font-size: 1.5rem;
  color: #2c3e50;
  margin: 0 0 15px 0;
  font-weight: 600;
  text-align: center;
}

.exam-meta {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  gap: 15px;
  font-size: 14px;
  color: #666;
}

.exam-meta span {
  padding: 5px 10px;
  background: #f5f5f5;
  border-radius: 4px;
}

/* 题型导航容器 */
.question-nav-container {
  margin-bottom: 20px;
}

/* 题型导航 - 智能固定版 */
.question-nav {
  display: flex;
  background: white;
  border-radius: 8px;
  border: 1px solid #e0e0e0;
  overflow: hidden;
  max-width: 1070px;
  margin: 0 auto;
}

.question-nav.sticky {
  position: fixed;
  top: 60px;
  left: 50%;
  transform: translateX(-50%);
  max-width: 1070px;
  width: calc(100vw - 40px);
  z-index: 100;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  border-radius: 0 0 8px 8px;
}

.nav-item {
  flex: 1;
  padding: 15px 20px;
  text-align: center;
  background: #f8f9fa;
  cursor: pointer;
  border-right: 1px solid #e0e0e0;
  font-weight: 500;
  color: #495057;
}

.nav-item:last-child {
  border-right: none;
}

.nav-item:hover {
  background: #e9ecef;
}

.nav-item.active {
  background: #007bff;
  color: white;
}

/* 题目区域 */
.section-title {
  font-size: 1.1rem;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 20px;
  padding: 15px 20px;
  background: #f8f9fa;
  border-left: 4px solid #007bff;
  border-radius: 4px;
}

.question-item {
  background: white;
  margin-bottom: 25px;
  padding: 25px;
  border-radius: 8px;
  border: 1px solid #e0e0e0;
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}

.question-number {
  font-size: 1.1rem;
  font-weight: 600;
  color: #007bff;
}

.question-status {
  font-size: 13px;
  padding: 4px 8px;
  border-radius: 12px;
  background: #f8d7da;
  color: #721c24;
}

.question-status.answered {
  background: #d4edda;
  color: #155724;
}

.question-content {
  font-size: 15px;
  line-height: 1.8;
  color: #2c3e50;
  margin-bottom: 20px;
  padding: 15px;
  background: #fafafa;
  border-radius: 4px;
  border-left: 3px solid #007bff;
}

/* KaTeX样式优化 */
.question-content :deep(.katex) {
  font-size: 1.1em;
  line-height: 1.5;
}

.question-content :deep(.katex-display) {
  margin: 1em 0;
  text-align: center;
}

.question-content :deep(.katex-error) {
  color: #d32f2f;
  background: #ffebee;
  padding: 2px 4px;
  border-radius: 3px;
  font-family: monospace;
}

/* 选择题选项 - 去边框平均分布版（修复背景色问题） */
.options-list {
  margin-top: 15px;
}

.options-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
  width: 100%;
}

.option-item {
  margin-bottom: 0;
  border-radius: 6px;
  overflow: hidden;
}

.option-item:hover {
  background: #f8f9ff;
}

.option-item :deep(.el-radio) {
  width: 100%;
  padding: 12px 15px;
  margin: 0;
  border-radius: 6px;
  overflow: hidden;
}

.option-item :deep(.el-radio:hover) {
  background: #f8f9ff;
}

.option-item :deep(.el-radio.is-checked) {
  background: #e8f4fd;
}

.option-item :deep(.el-radio__input) {
  margin-right: 10px;
}

.option-item :deep(.el-radio__label) {
  display: flex;
  align-items: flex-start;
  width: 100%;
  color: inherit;
  font-weight: normal;
  padding: 0;
  line-height: 1.5;
  overflow: hidden;
}

.option-label {
  font-weight: 600;
  margin-right: 8px;
  color: #007bff;
  flex-shrink: 0;
}

.option-text {
  flex: 1;
  line-height: 1.8;
  word-wrap: break-word;
}

/* 选项中的KaTeX样式 */
.option-text :deep(.katex) {
  font-size: 1em;
  line-height: 1.5;
}

.option-text :deep(.katex-display) {
  margin: 0.5em 0;
  text-align: left;
}

/* 题型跳转按钮 - 简化版 */
.type-navigation {
  margin-top: 25px;
  padding: 20px;
  background: linear-gradient(135deg, #f8f9fa, #e9ecef);
  border-radius: 8px;
  border: 1px solid #dee2e6;
  text-align: center;
}

.navigation-buttons {
  display: flex;
  justify-content: center;
  gap: 15px;
}

.answer-input {
  margin-top: 15px;
}

.fill-input,
.subjective-input {
  border-radius: 6px;
}

.fill-input :deep(.el-input__wrapper) {
  padding: 10px 15px;
}

.subjective-input :deep(.el-textarea__inner) {
  padding: 15px;
  line-height: 1.6;
}

/* 右侧答题卡 - 简化版 */
.answer-card {
  width: 280px;
  flex-shrink: 0;
  background: white;
  border-radius: 8px;
  border: 1px solid #e0e0e0;
  position: sticky;
  top: 80px;
  height: fit-content;
  max-height: calc(100vh - 100px);
  overflow: hidden;
}

.card-header {
  background: #f8f9fa;
  padding: 15px 20px;
  border-bottom: 1px solid #e0e0e0;
}

.card-title {
  font-size: 1rem;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 8px;
}

.progress-text {
  font-size: 14px;
  color: #666;
}

.progress-numbers {
  font-weight: 600;
  color: #007bff;
}

.card-body {
  padding: 15px;
  max-height: calc(100vh - 200px);
  overflow-y: auto;
}

.question-type-section {
  margin-bottom: 20px;
}

.type-title {
  font-size: 14px;
  font-weight: 600;
  color: #495057;
  margin-bottom: 10px;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.question-grid {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 8px;
}

.question-number-btn {
  width: 32px;
  height: 32px;
  line-height: 32px;
  text-align: center;
  border-radius: 4px;
  background: #f8f9fa;
  color: #495057;
  font-size: 13px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  border: 1px solid #e0e0e0;
}

.question-number-btn:hover {
  background: #e9ecef;
  border-color: #adb5bd;
}

.question-number-btn.answered {
  background: #28a745;
  color: white;
  border-color: #28a745;
}

.question-number-btn.current {
  background: #dc3545;
  color: white;
  border-color: #dc3545;
}

/* 提交按钮 */
.card-footer {
  padding: 15px;
  border-top: 1px solid #e0e0e0;
  background: #f8f9fa;
}

.submit-button {
  width: 100%;
  padding: 12px 0;
  font-size: 15px;
  font-weight: 600;
  border-radius: 6px;
}

/* 加载和错误状态 */
.loading-container {
  height: 60vh;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  gap: 15px;
}

.loading-text {
  color: #666;
  font-size: 16px;
}

.error-alert {
  margin-bottom: 20px;
}

/* 提交确认对话框样式 */
:global(.submit-confirm-dialog) {
  border-radius: 12px !important;
}

:global(.submit-confirm-dialog .el-message-box__header) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 12px 12px 0 0;
  padding: 20px 24px 16px;
}

:global(.submit-confirm-dialog .el-message-box__title) {
  color: white;
  font-weight: 600;
  font-size: 16px;
}

:global(.submit-confirm-dialog .el-message-box__content) {
  padding: 24px;
}

:global(.submit-confirm-dialog .el-message-box__btns) {
  padding: 16px 24px 24px;
  border-top: 1px solid #f0f0f0;
}

:global(.submit-confirm-dialog .el-button--primary) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  font-weight: 600;
}

:global(.submit-confirm-dialog .el-button--primary:hover) {
  background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .exam-content-wrapper {
    flex-direction: column;
  }

  .answer-card {
    width: 100%;
    position: static;
    margin-top: 20px;
  }

  .question-nav {
    max-width: none;
    width: 100%;
  }

  .question-nav.sticky {
    max-width: none;
    width: calc(100vw - 30px);
  }

  .options-grid {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .exam-container {
    padding: 80px 15px 20px 15px;
  }

  .exam-meta {
    justify-content: center;
    text-align: center;
  }

  .exam-meta span {
    flex: 1 1 auto;
    text-align: center;
  }

  .question-nav {
    flex-direction: column;
    width: 100%;
  }

  .question-nav.sticky {
    width: calc(100vw - 20px);
  }

  .nav-item {
    border-right: none;
    border-bottom: 1px solid #e0e0e0;
  }

  .nav-item:last-child {
    border-bottom: none;
  }

  .question-item {
    padding: 20px 15px;
  }

  .question-grid {
    grid-template-columns: repeat(5, 1fr);
  }

  .options-grid {
    grid-template-columns: 1fr;
    gap: 8px;
  }

  .type-navigation {
    padding: 15px;
  }

  .navigation-buttons {
    flex-direction: column;
    gap: 10px;
  }
}

@media (max-width: 480px) {
  .countdown-timer {
    font-size: 1.2rem;
  }

  .exam-title {
    font-size: 1.3rem;
  }

  .question-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .question-grid {
    grid-template-columns: repeat(4, 1fr);
  }

  .question-nav.sticky {
    width: calc(100vw - 10px);
  }

  .type-navigation {
    padding: 12px;
  }

  .navigation-buttons {
    gap: 8px;
  }
}

/* KaTeX全局样式优化 */
:deep(.katex) {
  overflow-x: auto;
  overflow-y: hidden;
  max-width: 100%;
}

:deep(.katex-display) {
  overflow-x: auto;
  overflow-y: hidden;
  padding: 0.5em 0;
}

/* 确保KaTeX在所有容器中都能正确显示 */
:deep(.katex .mord),
:deep(.katex .mrel),
:deep(.katex .mop),
:deep(.katex .mbin),
:deep(.katex .mpunct),
:deep(.katex .mopen),
:deep(.katex .mclose) {
  color: inherit;
}
</style>